#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from fastapi import APIRouter, HTTPException, Query, Body
from app.service.projectsvc.project_service import ProjectService
from app.types.apiproto.project_proto import (
    ProjectCreate,
    ProjectUpdate,
    ProjectDetail,
    ProjectListResponse,
    ProjectIdRequest
)

router = APIRouter(prefix="/project", tags=["项目管理"])

@router.post("/create", response_model=ProjectDetail)
async def create_project(req: ProjectCreate):
    """
    创建项目
    """
    try:
        result = ProjectService.create_project(req)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建项目失败: {str(e)}")


@router.post("/update", response_model=bool)
async def update_project(req: ProjectUpdate):
    """
    更新项目
    """
    try:
        result = ProjectService.update_project(req)
        if not result:
            raise HTTPException(status_code=404, detail="项目不存在或更新失败")
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新项目失败: {str(e)}")


@router.get("/detail/{project_id}", response_model=ProjectDetail)
async def get_project_detail(project_id: str):
    """
    获取项目详情
    """
    try:
        result = ProjectService.get_project_by_id(project_id)
        if not result:
            raise HTTPException(status_code=404, detail="项目不存在")
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取项目详情失败: {str(e)}")


@router.get("/list", response_model=ProjectListResponse)
async def list_projects(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    project_number: str = Query("", description="项目号"),
    project_type: str = Query("", description="项目类型"),
    status: str = Query("", description="项目状态")
):
    """
    获取项目列表
    """
    try:
        result = ProjectService.list_projects(page, page_size, project_number, project_type, status)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取项目列表失败: {str(e)}")


@router.post("/delete", response_model=bool)
async def delete_project(req: ProjectIdRequest):
    """
    删除项目
    """
    try:
        result = ProjectService.delete_project(req.id)
        if not result:
            raise HTTPException(status_code=404, detail="项目不存在或删除失败")
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除项目失败: {str(e)}")